package com.itwxz.forum.controller.mobile;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.util.SaResult;
import com.itwxz.common.constant.CacheConstants;
import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.common.exception.user.CaptchaException;
import com.itwxz.common.exception.user.CaptchaExpireException;
import com.itwxz.common.utils.MailSenderUtils;
import com.itwxz.common.utils.StringUtils;
import com.itwxz.forum.domain.dto.ForumEmailCodeDto;
import com.itwxz.forum.domain.dto.RegisterForumDto;
import com.itwxz.forum.service.ForumRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/forum/mobile")
public class ForumRegisterController {
    @Autowired
    private ForumRegisterService registerService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private MailSenderUtils mailSender;

    /**
     * 验证图片验证码，邮箱发送验证码
     */
    @SaIgnore
    @PostMapping("/sendCode")
    public SaResult sendCode(@RequestBody ForumEmailCodeDto emailCode) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(emailCode.getUuid(), "");
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) throw new CaptchaExpireException();
        if (!emailCode.getCode().equalsIgnoreCase(captcha)) throw new CaptchaException();

        String uuid = mailSender.sendVerifyCodeMail(emailCode.getEmail());
        return SaResult.ok("验证码发送成功！").set("uuid", uuid);
    }

    /**
     * 注册用户
     * @param registerForumDto 注册所需数据
     * @return 无
     */
    @SaIgnore
    @PostMapping("/register")
    public SaResult register(@RequestBody RegisterForumDto registerForumDto) {
        return registerService.register(registerForumDto);
    }

}
